package com.siashan.unipay4j.ali.pay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.siashan.unipay4j.ali.AbstractAliPay;
import com.siashan.unipay4j.core.pay.IClose;
import com.siashan.unipay4j.core.IPayConfig;
import com.siashan.unipay4j.core.Result;
import lombok.extern.slf4j.Slf4j;

/**
 * 用于交易创建后，用户在一定时间内未进行支付，可调用该接口直接将未付款的交易进行关闭。
 *
 * @author  siashan
 * @since  v1.0.1
 **/
@Slf4j
public class AliPayClose extends AbstractAliPay implements IClose {

    public AliPayClose() {
    }

    public AliPayClose(IPayConfig payConfig) {
        super(payConfig);
    }

    /**
     * 关闭订单
     *
     * @param outTradeNo  平台支付流水号
     * @return   关闭结果
     */
    @Override
    public Result execClose(String outTradeNo) {
        log.info("AliClose::=>关闭订单请求到达,订单号{}", outTradeNo);
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        request.setBizContent("{\" out_trade_no \":\"" + outTradeNo + "\"}");
        try {
            AlipayTradeCloseResponse r = alipayClient.execute(request);
            if (r.isSuccess()) {
                log.info("AliClose::=>关闭订单请求成功,订单号{}", outTradeNo);
                return Result.tradeSuccess(r);
            } else {
                log.info("AliClose::=>关闭订单请求失败,订单号{}，错误代码{}，错误原因{}", outTradeNo, r.getSubCode(), r.getSubMsg());
                return Result.tradeFail(r.getSubCode(), r.getSubMsg());
            }
        } catch (AlipayApiException e) {
            log.warn("AliClose::=>关闭订单异常,订单号{}", outTradeNo, e);
        }
        return Result.exception();
    }
}
